<?php

namespace App\Http\Controllers\Frontend\V10\Message;

use App\Models\HeaderMessage;
use App\Models\HeaderMessageReadeds;
use App\Models\NewsMessage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class NewsMessageController extends Controller
{
    public function __construct()
    {
        //$this->middleware('auth:api');
    }

    public function list()
    {


        $now = date('Y-m-d H:i:s');
        $data['newsMessage'] = NewsMessage::select('content')
             ->where('is_show',1)
             ->orderBy('id','desc')
             ->first();

        if($data['newsMessage']) {
            $data['newsMessage']['content'] = preg_split('/[\r\n\t]/',$data['newsMessage']['content']);
            $data['newsMessage']['switch'] = 'on';
        }else{
            $data['newsMessage']['switch'] = 'off';
        }

        $data['headerMessage'] = HeaderMessage::select('id','content','desc','title','is_h5','url')
         ->where('status',1)
         ->where('valid_time','>=',$now)
         ->orderBy('id','desc')
         ->first();

        if($data['headerMessage']) {
            if(Auth::check()) {
                $user_id = Auth::user()->id;
                $is_read = HeaderMessageReadeds::where('user_id', $user_id)->where('msg_id', $data['headerMessage']['id'])->first();
                $data['headerMessage']['is_read'] = $is_read ? 1 : 2;
            } else {
                $data['headerMessage']['is_read'] = 1;
            }
            $data['headerMessage']['switch'] = 'on';
        } else {
            $data['headerMessage']['switch'] = 'off';
        }

        return success($data);
    }
}
